package 剑指offer;

import 抽象数据类型.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Queue;

/**
 * @description:
 * @author: ywk
 * @date: 2021-02-19
 */
public class 二叉树的之字形层序遍历 {
    /**
     * @param root TreeNode类
     * @return int整型ArrayList<ArrayList                               <>>
     */
    public static ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new ArrayDeque();
        queue.offer(root);
        boolean order = false;//顺序
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            while (size-- > 0) {
                TreeNode temp = queue.poll();
                list.add((int) temp.val);
                if (temp.left != null) {
                    queue.offer(temp.left);
                }
                if (temp.right != null) {
                    queue.offer(temp.right);
                }
            }
            if (order) {
                Collections.reverse(list);
            }
            result.add(list);
            order = !order;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(zigzagLevelOrder(null));

    }
}
